import { useNavigator } from "./navigator";
import { useStore } from "vuex";
import { useI18n } from "vue-i18n";
import { systemInfo } from "../tools/system.js";
import { ref, onMounted, computed, watchEffect } from "vue";

// 跳转到配置信息编辑页面
export const useSetting = () => {
  const { store, toSettingEdit } = useNavigator();
  return { toSettingEdit };
};

export function useLanState(store) {
  if (!store) store = useStore();

  const { locale } = useI18n();
  const language = ref(store.getters["config/getLan"]);

  function setLanguage(lan = "en") {
    locale.value = lan;
    language.value = lan;
    store.dispatch("config/changeLanguage", lan);
  }

  return [language, setLanguage];
}

export function useThemeState(store) {
  if (!store) store = useStore();
  const isDark = ref(!store.getters["config/isLight"]);

  function setTheme() {
    const next = isDark.value ? "dark" : "light";
    store.dispatch("config/changeTheme", next);
  }

  return [isDark, setTheme];
}

/** 用户退出 */
export const useLogout = (store) => {
  if (!store) store = useStore();

  const toLogout = async () => {
    await store.dispatch("user/resetUserInfo");
    uni.reLaunch({ url: "/pages/member/login/login" });
  };

  return { toLogout };
};

/**
 * 显示/隐藏 模态框
 * @returns {[ state: ref<any>, handle: () => void ]}
 */
export const useComModel = () => {
  const showModel = ref(false);

  function handleModel() {
    showModel.value = !showModel.value;
  }

  return [showModel, handleModel];
};

/** 获取最小内容页高度
 * @param {Boolean} full 是否包含底部
 * @returns {String} 高度样式 '1px'
 */
export const useContentHeight = (full /** true | false */) => {
  const minHeight = ref(0);

  onMounted(() => {
    const { windowHeight, windowTop, windowBottom } = systemInfo();
    minHeight.value = windowHeight - windowTop - (full ? 0 : windowBottom) + "px";
  });

  return minHeight;
};

/** 用户登录状态
 * @returns {[isLogin, store]}
 */
export const useLoginState = (store) => {
  if (!store) store = useStore();
  const isLogin = ref(false);

  const loginState = computed(() => {
    return store.getters["user/isLogin"];
  });

  watchEffect(() => {
    isLogin.value = loginState.value;
  });

  return [isLogin, store];
};
